package com.wonders.module.auth.controller;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.wonders.common.constant.CommonConstant;
import com.wonders.common.constant.TipConstant;
import com.wonders.framework.util.ValidateUtil;
import com.wonders.framework.util.web.RequestUtil;
import com.wonders.framework.web.BaseController;
import com.wonders.module.auth.entity.vo.MenuVo;
import com.wonders.module.auth.service.MenuService;

/**
 * 菜单控制层
 * 
 * @author WuBin
 * 
 */
@Controller
@RequestMapping("/auth/menu")
public class MenuController extends BaseController {

	@Autowired
	private MenuService menuService;

	/**
	 * 导航到菜单编辑页面
	 * 
	 * @return
	 */
	@RequestMapping("toQuery")
	public Object toQuery() {
		return "auth/menuList";
	}

	/**
	 * 查询菜单信息
	 * 
	 * @return
	 */
	@RequestMapping("query")
	@ResponseBody
	public Object query() {
		MenuVo menuVo = RequestUtil.requestParamToBean(MenuVo.class);
		menuVo.setEnable(CommonConstant.Status.ENABLED);
		return menuService.query(menuVo);
	}

	/**
	 * 保存菜单信息
	 * 
	 * @return
	 */
	@RequestMapping("save")
	@ResponseBody
	public Object save() {
		MenuVo menuVo = RequestUtil.requestParamToBean(MenuVo.class);
		String action = (String) RequestUtil.getRequestParam("action");
		System.out.println(action + ":" + menuVo);
		if (StringUtils.isEmpty(action)
				|| !ValidateUtil.nullCheck(menuVo, "name")) {
			return super.ajaxError(TipConstant.PARAM.MISSING);
		}
		if (CommonConstant.Action.EDIT.equals(action)) {
			if (!ValidateUtil.nullCheck(menuVo, "id")) {
				return super.ajaxError(TipConstant.PARAM.MISSING);
			}
			menuService.update(menuVo);
		} else if (CommonConstant.Action.ADD.equals(action)) {
			menuService.save(menuVo);
		} else {
			return super.ajaxError(TipConstant.PARAM.INVALID);
		}
		return super.ajaxSuccess();
	}

	/**
	 * 加载菜单信息
	 * 
	 * @return
	 */
	@RequestMapping("load")
	@ResponseBody
	public Object load() {
		MenuVo menuVo = RequestUtil.requestParamToBean(MenuVo.class);
		if (!ValidateUtil.nullCheck(menuVo, "id")) {
			return super.ajaxError(TipConstant.PARAM.MISSING);
		}
		menuVo = menuService.load(menuVo.getId());
		return super.ajaxSuccess(menuVo);
	}

	/**
	 * 删除菜单信息
	 * 
	 * @return
	 */
	@RequestMapping("remove")
	@ResponseBody
	public Object remove() {
		MenuVo menuVo = RequestUtil.requestParamToBean(MenuVo.class);
		if (!ValidateUtil.nullCheck(menuVo, "id")) {
			return super.ajaxError(TipConstant.PARAM.MISSING);
		}
		menuService.remove(menuVo.getId());
		return super.ajaxSuccess();
	}

}
